<template>
  <div class="page">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <div class="info-group">
              <el-button class="add-btn" type="primary" @click="openDialog('add',null)">新增</el-button>
              <span class="total-count">共计{{ total }}条</span>
              <span class="warning">1和2数据较多</span>
            </div>
          </div>
          <div class="right">
            <el-form inline @submit.prevent>
              <el-form-item label="课程名">
                <el-input
                  v-model="searchForm.name"
                  placeholder="请输入课程名"
                  clearable
                  @clear="resetSearch"
                  @keyup.enter="handleSearch" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="clientData"
        style="width: 100%"
        empty-text="暂无数据"
        :table-layout="tableLayout">
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="name" label="课程名称" />
        <el-table-column prop="credit" label="学分" />
        <el-table-column prop="description" label="课程描述" />
        <el-table-column
          label="操作">
          <template #default="data">
            <div class="icon-group">
              <el-tooltip effect="light" content="编辑" placement="top">
                <el-button icon="Edit" type="primary" @click="openDialog('edit', data.row.id)" />
              </el-tooltip>
              <el-tooltip effect="light" content="查看班级" placement="top">
                <el-button icon="View" type="warning" @click="handleView(data.row.id)" />
              </el-tooltip>
              <el-tooltip effect="light" content="删除" placement="top">
                <el-button icon="Delete" type="danger" @click="handleDelete(data.row.id)" />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="current"
        v-model:page-size="pageSize"
        background
        layout="total,  prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </el-card>
  </div>
  <el-dialog v-model="dialogVisible" :title="dialogFormTitle">
    <el-form ref="formRef" :model="dialogForm">
      <el-form-item label="名称" prop="name">
        <el-input v-model="dialogForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="学分"
        prop="credit"
        type="number"
        min="0"
        max="5">
        <el-input v-model="dialogForm.credit" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="dialogForm.description" autocomplete="off" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm(dialogFormTitle === '新增课程' ? 'add' : 'edit')">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { getCourseList, addCourse, updateCourse, deleteCourse } from '@/api/course'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useCourseStore } from '../../stores/course'
const courseStore = useCourseStore()
const router = useRouter()
const total = ref(0)
const tableLayout = ref('auto')
const clientData = ref([])
// 存储所有数据用于本地分页
const allData = ref([])
// 当前页数
const current = ref(1)
// 每页的显示条数
const pageSize = ref(10)
// 表格加载状态
const loading = ref(false)
// 框框的显示与隐藏
const dialogVisible = ref(false)

// 搜索相关
const searchForm = reactive({
  name: ''
})
// 对话框标题
const dialogFormTitle = ref('')
// 对话框表单数据
const dialogForm = reactive({
  id: null,
  name: '',
  credit: '',
  description: ''
})
// 表单元素
const formRef = ref(null)

// 加载数据方法
const loadData = async () => {
  // 加载数据显示加载状态
  loading.value = true
  try {
    const res = await getCourseList()
    if (res.status === 200) {
      allData.value = res.data.list || []
      total.value = res.data.total || allData.value.length
      applyLocalSearchAndPagination()
    } else {
      ElMessage.error('加载课程列表失败')
    }
    loading.value = false
  } catch (error) {
    ElMessage.error(error.message || '获取课程列表失败')
    loading.value = false
  }
}

const handleView = (id) => {
  // TODO :点击详情前往 该课程下的班级详情页
  courseStore.setClazzId(id)
  courseStore.setCourseName(allData.value.find(item => item.id === id).name)
  router.push('/clazz_course')
}
// 本地搜索和分页函数
const applyLocalSearchAndPagination = () => {
  // 定义准备过滤的数据集
  let filteredData = allData.value

  // 本地搜索过滤
  if (searchForm.name.trim()) {
    filteredData = filteredData.filter(item =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }

  // 设置总数
  total.value = filteredData.length

  // 本地分页
  const start = (current.value - 1) * pageSize.value
  const end = start + pageSize.value
  clientData.value = filteredData.slice(start, end)
}
const handleCurrentChange = value => {
  current.value = value
  applyLocalSearchAndPagination()
}

const handleSizeChange = value => {
  pageSize.value = value
  current.value = 1
  applyLocalSearchAndPagination()
}
// 搜索处理函数
const handleSearch = () => {
  current.value = 1 // 搜索时重置到第一页
  applyLocalSearchAndPagination()
}
// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.credit = ''
  current.value = 1
  applyLocalSearchAndPagination()
}
// 删除处理函数
const handleDelete = async id => {
  try {
    await ElMessageBox.confirm('确定要删除这条课程数据吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用删除API
    const res = await deleteCourse(id)
    if (res.status === 200) {
      // 从本地数据中删除
      const index = allData.value.findIndex(item => item.id === id)
      if (index > -1) {
        allData.value.splice(index, 1)
      }
    } else {
      ElMessage.error(res.msg || '删除课程失败')
      return
    }

    // 智能分页处理 - 当删除当前页最后一条数据时，自动跳转到上一页
    if (current.value > 1 && clientData.value.length === 1) {
      current.value--
    }

    ElMessage.success('删除成功!')

    // 重新应用本地搜索和分页
    applyLocalSearchAndPagination()
  } catch (error) {
    // 错误处理，区分用户取消和API调用失败
    if (error === 'cancel') {
      // 用户点击取消，不做任何操作
      console.log('用户取消了删除操作')
    } else {
      // API调用失败
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

const openDialog = (model, id) => {
  dialogFormTitle.value = model === 'add' ? '新增课程' : '编辑课程'
  dialogForm.id = id
  if (model === 'add') {
    dialogForm.name = ''
    dialogForm.credit = ''
    dialogForm.description = ''
  } else {
    // 编辑模式，根据id从allData中找到对应数据填充到dialogForm
    const course = allData.value.find(item => item.id === id)
    if (course) {
      dialogForm.name = course.name
      dialogForm.credit = course.credit
      dialogForm.description = course.description
    }
  }
  dialogVisible.value = true
}
const submitForm = async (model) => {
  try {
    await formRef.value.validate()
    if (model === 'add') {
      await addCourse({
        name: dialogForm.name,
        credit: dialogForm.credit,
        description: dialogForm.description
      })
    } else {
      await updateCourse(
        dialogForm.id,
        { name: dialogForm.name,
          credit: dialogForm.credit,
          description: dialogForm.description
        })
    }
    ElMessage.success('操作成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error(error.message || '更新课程失败')
  }
}
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;
    align-items: center;
    gap: 12px;

    .info-group {
      display: flex;
      align-items: center;
      gap: 8px;

      .total-count {
        font-size: 0.7rem;
        font-weight: 500;
        color: #606266;
        background: #f5f7fa;
        padding: 2px 8px;
        border-radius: 2px;
      }

      .warning {
        font-size: 0.65rem;
        font-weight: 500;
        color: #f56c6c;
        background: #fef0f0;
        padding: 2px 8px;
        border-radius: 2px;
      }
    }
  }

  .right {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.icon-group {
  display: flex;
  gap: 8px;

  .el-button {
    padding: 4px 8px;
  }
}

.warning {
  font-size: 0.8rem;
  color: red;
}
</style>
